package edu.bw.mapper;

import org.apache.ibatis.annotations.*;
import po.Product;

import java.util.List;

public interface ProductMapper {
    /**
     * selectKey:作用是用于不指定主键的参数时，获取数据库自动维护的主键值然后插入
     * keyProperty:主键对应属性
     * keyColumn:主键列
     * resultType:主键的java类型
     * statement:执行的语句
     * before:true,在插入语句之前查询主键,false在插入语句之后查询主键
     * @param product
     */
    @SelectKey(keyProperty = "id", keyColumn = "id", resultType = int.class
            , statement = "SELECT LAST_INSERT_ID()", before = false)
    @Insert("INSERT INTO mybatis02.product(name, price, detail, pic, createtime) VALUES " +
            "(#{name},#{price},#{detail},#{pic},#{createtime})")
    void saveProduct(Product product);

    /**
     * 修改商品
     * @param product 修改的商品
     */
    @Update("UPDATE mybatis02.product SET name = #{name} ,price = #{price} ,detail = #{detail},pic = #{pic} ,createtime = #{createtime} " +
            "WHERE id = #{id} ")
    void updateProduct(Product product);

    /**
     * 删除商品
     * @param id 商品的id
     */
    @Delete("DELETE FROM mybatis02.product WHERE id = #{id} ")
    void deleteProduct(Integer id);

    /**
     * 查询所有商品
     * @return 所有商品
     */
    @Select("SELECT * FROM mybatis02.product")
    List<Product> findAll();

    /**
     * 根据id查询商品
     * //@Results:相当于配置文件中的<resultMap>标签
     * //@Results中的id属性相当于<resultMap id = xxx>
     * //@Result:相当于配置文件中的<result>标签
     * //@Result 注解中的id属性 相当于映射文件中的 <id></id>
     * @param id
     * @return
     */
    @Results({
            @Result(column = "pid",property = "id",id = true),//当映射主键时要将id的属性设置为true
            @Result(column = "pname",property = "name")
    })
    @Select("SELECT id AS pid,name AS pname, price, detail, pic, createtime FROM mybatis02.product WHERE id = #{id} ")
    Product findById(int id);
}
